package org.shuma.user.mng.utils;

import org.shuma.user.mng.domain.entity.User;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author zhao haitao
 * @date 2024/06/17 1:25 AM
 */
@Component
public class RedisUtil {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    // 操作字符串类型数据
    public void set(String key, String value, long time) {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set(key, value);
        if (time > 0) {
            redisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
    }

    public Long getExpire(String key) {
        if (Boolean.FALSE.equals(redisTemplate.hasKey(key))) return 0L;
        return redisTemplate.getExpire(key);
    }

    public String get(String key) {
        if (Boolean.FALSE.equals(redisTemplate.hasKey(key))) {
            return null;
        }
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        return operations.get(key);
    }

    // 删除键
    public Boolean delete(String key) {
        if (Boolean.FALSE.equals(redisTemplate.hasKey(key))) return false;
        return redisTemplate.delete(key);
    }

    // 操作哈希类型数据

    /**
     *
     * @param token token
     * @param user 用户信息
     * @param expireTime 过期时间(s)
     */
    public void setUserInfo(String token, User user, long expireTime) {
        if (expireTime > 0) {
            HashOperations<String, String, User> hashOperations = redisTemplate.opsForHash();
//            根据用户名保存用户信息
            HashMap<String, User> hashMap = new HashMap<>();
            hashMap.put("user", user);
            hashOperations.putAll(user.getUserName(), hashMap);
            redisTemplate.expire(user.getUserName(), expireTime, TimeUnit.SECONDS);
//            根据token保存用户名
            redisTemplate.opsForValue().set(token, user.getUserName(), expireTime, TimeUnit.SECONDS);
        }
    }

    /**
     * 获取用户信息
     * @param token token
     * @return 用户信息
     */
    public User getUserInfo(String token) {
        if (Boolean.FALSE.equals(redisTemplate.hasKey(token))) {
            return null;
        }
        HashOperations<String, String, User> hashOperations = redisTemplate.opsForHash();
        return hashOperations.entries(Objects.requireNonNull(redisTemplate.opsForValue().get(token))).get("user");
    }


}